package app.util;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.app.R;

public class TransferLayout extends FrameLayout
{
    public TransferLayout(Context context){
        super(context);
        init(context, null);
    }

    public TransferLayout(Context context, AttributeSet attrs){
        super(context, attrs);
        init(context, attrs);
    }

    public TransferLayout(Context context, AttributeSet attrs, int defStyleAttr){
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    void init(Context context, AttributeSet attrs){

    }

    @Override
    public void onViewAdded(View child){
        super.onViewAdded(child);
        if(child.getLayoutParams() instanceof LayoutParams){
            LayoutParams lp = (LayoutParams)child.getLayoutParams();
            ViewGroup target = findViewById(lp.target);
            if(target == null) return;
            if(target == this) return;
            this.removeView(child);
            if(lp.exclusive) target.removeAllViews();
            target.addView(child);
        }
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams(){
        return new LayoutParams(-2, -2);
    }

    @Override
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp){
        return new LayoutParams(lp.width, lp.height);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs){
        return new LayoutParams(getContext(), attrs);
    }

    public static class LayoutParams extends FrameLayout.LayoutParams
    {
        public int target = View.NO_ID;
        public boolean exclusive = false;

        public LayoutParams(int width, int height){
            super(width, height);
        }

        public LayoutParams(Context context, AttributeSet attrs){
            super(context, attrs);
            TypedArray ta =
                context.obtainStyledAttributes(attrs, R.styleable.TransferLayout_Layout);
            target = ta.getResourceId(R.styleable.TransferLayout_Layout_transferTo, target);
            exclusive =
                ta.getBoolean(R.styleable.TransferLayout_Layout_transferExclusive, exclusive);
            ta.recycle();
        }
    }

}
